package com.ruoyi.passenger.pay.util;

import cn.hutool.core.lang.Console;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.order.HttpClientUtil;
import com.ruoyi.common.utils.order.OrderUtil;
import com.ruoyi.management.basics.vo.DriverMerListVo;
import com.ruoyi.passenger.pay.ro.QrURLDemo;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.ruoyi.passenger.pay.vo.PayLogsVO;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class PayUtils
{


    public static final String RETURN_CODE="000000";//交易返回码，成功时总为 000000

    /**
     * 获取支付结果
     * @param driverMer
     * @param bankURL
     */
    public static PayLogsVO sendQryResult(DriverMerListVo driverMer, String bankURL, String ORDERID, String QUPWD)
    {
        AjaxResult ajax = AjaxResult.success();
        String MERCHANTID = driverMer.getMerchantid();//商户代码
        String POSID = driverMer.getPostid();//柜台号
        String BRANCHID = driverMer.getBranchid();//分行代码
        String ORDERDATE="";//定单日期
        String BEGORDERTIME="";//定单开始时间
        String ENDORDERTIME="";//定单截止时间
        String BEGORDERID="";//开始订单号
        String ENDORDERID="";//结束订单号
        String TXCODE="410408";//交易码
        String SEL_TYPE="3";//查询方式 3 XML 页面形式
        String OPERATOR="";//操作员

        //txcode=410408
        String TYPE="0";//流水类型 0 支付流水 1 退款流水
        String KIND="0";//0 未结算流水 1 已结算流水 当日只有未结算流水可供查询
        String STATUS="1";//交易状态 0失败 1成功 2 不确定 3 全部

        String PAGE = "1";
        String CHANNEL = "";

        String param ="MERCHANTID="+MERCHANTID+"&BRANCHID="+BRANCHID+"&POSID="+POSID+"&ORDERDATE="+ORDERDATE+"&BEGORDERTIME="+BEGORDERTIME
                +"&ENDORDERTIME="+ENDORDERTIME+"&BEGORDERID="+BEGORDERID+"&ENDORDERID="+ENDORDERID+"&QUPWD=&TXCODE="+TXCODE
                +"&SEL_TYPE="+SEL_TYPE+"&OPERATOR="+OPERATOR;

        if("410408".equals(TXCODE)){
            param ="MERCHANTID="+MERCHANTID+"&BRANCHID="+BRANCHID+"&POSID="+POSID+"&ORDERDATE="
                    +ORDERDATE+"&BEGORDERTIME="+BEGORDERTIME+"&ENDORDERTIME="+ENDORDERTIME+"&ORDERID="
                    +ORDERID+"&QUPWD=&TXCODE="+TXCODE+"&TYPE="+TYPE+"&KIND="+KIND+"&STATUS="+STATUS+
                    "&SEL_TYPE="+SEL_TYPE+"&PAGE="+PAGE+"&OPERATOR="+OPERATOR+"&CHANNEL="+CHANNEL;
        }
        System.out.println("-----"+MD5.md5Str(param));

        Map map = new HashMap();
        map.put("MERCHANTID",MERCHANTID);

        map.put("BRANCHID",BRANCHID);
        map.put("POSID",POSID);

        map.put("ORDERDATE",ORDERDATE);

        map.put("BEGORDERTIME",BEGORDERTIME);

        map.put("ENDORDERTIME",ENDORDERTIME);

        map.put("BEGORDERID",BEGORDERID);

        map.put("ENDORDERID",ENDORDERID);

        map.put("QUPWD",QUPWD);

        map.put("TXCODE",TXCODE);

        if("410408".equals(TXCODE)){
            map.put("TYPE",TYPE);
            map.put("KIND",KIND);
            map.put("STATUS",STATUS);
            map.put("ORDERID",ORDERID);
            map.put("PAGE",PAGE);
            map.put("CHANNEL",CHANNEL);
        }


        map.put("SEL_TYPE",SEL_TYPE);

        map.put("OPERATOR",OPERATOR);

        map.put("MAC",MD5.md5Str(param));

        System.out.println(bankURL);
        String ret = HttpClientUtil.httpPost(bankURL, map);
        System.out.println("ret::"+ret);
        PayLogsVO vo = new PayLogsVO();
        vo.setCallDate(new Date());
        vo.setPayResult(readStringXml(ret));
        vo.setLog(ret.trim());
        return vo;

    }


    /**
     * 获取支付地址
     * @param driverMer
     * @param payment
     * @return
     */
    public static AjaxResult  sendPayUrlInfo(DriverMerListVo driverMer,String payment,String curCode,String txCode,String bankURL,String RETURNTYPE)
    {

        AjaxResult ajax = AjaxResult.success();
        String MERCHANTID = driverMer.getMerchantid();
        String POSID = driverMer.getPostid();
        String BRANCHID = driverMer.getBranchid();
        String ORDERID = OrderUtil.getBankLsh(MERCHANTID);
        String REMARK1 = "";
        String REMARK2 = "";
        String TIMEOUT = "";
        String PUB32TR2= driverMer.getPub32tr2();

        StringBuffer tmp = new StringBuffer();
        tmp.append("MERCHANTID=");
        tmp.append(MERCHANTID);
        tmp.append("&POSID=");
        tmp.append(POSID);
        tmp.append("&BRANCHID=");
        tmp.append(BRANCHID);
        tmp.append("&ORDERID=");
        tmp.append(ORDERID);
        tmp.append("&PAYMENT=");
        tmp.append(payment);
        tmp.append("&CURCODE=");
        tmp.append(curCode);
        tmp.append("&TXCODE=");
        tmp.append(txCode);
        tmp.append("&REMARK1=");
        tmp.append(REMARK1);
        tmp.append("&REMARK2=");
        tmp.append(REMARK2);
        tmp.append("&RETURNTYPE=");
        tmp.append(RETURNTYPE);
        tmp.append("&TIMEOUT=");
        tmp.append(TIMEOUT);
        tmp.append("&PUB=");
        tmp.append(PUB32TR2);

        Map map = new HashMap();
        map.put("CCB_IBSVersion","V6");
        map.put("MERCHANTID",MERCHANTID);
        map.put("BRANCHID",BRANCHID);
        map.put("POSID",POSID);
        map.put("ORDERID",ORDERID);
        map.put("PAYMENT",payment);
        map.put("CURCODE",curCode);
        map.put("TXCODE",txCode);
        map.put("REMARK1",REMARK1);
        map.put("REMARK2",REMARK2);
        map.put("RETURNTYPE",RETURNTYPE);
        map.put("TIMEOUT",TIMEOUT);
        map.put("MAC", MD5.md5Str(tmp.toString()));

        String ret = HttpClientUtil.httpPost(bankURL, map);
        System.out.println("ret::"+ret);
        Gson gson = new Gson();
        try
        {
            QrURLDemo payUrlVo = (QrURLDemo) gson.fromJson(ret, QrURLDemo.class);

            if (null != payUrlVo && "true".equals(payUrlVo.getSUCCESS()))
            {
                ajax = AjaxResult.success();
                ajax.put("payUrl",payUrlVo.getPAYURL()).put("orderId",ORDERID);
                ajax.put("result","success");
            }
            else {
                ajax.put("result","error");
                ajax.put("msg","支付失败，请选择其他支付方式");
                System.out.println("获取qrurl失败"+payUrlVo.getSUCCESS());
            }
        }catch (Exception e)
        {
            ajax.put("result","error");
            ajax.put("msg","支付失败，请选择其他支付方式");
        }

        return ajax;
    }


    /**
     * 解析xml文件
     * @param xml
     */
    public static String readStringXml(String xml) {

        String statusCode  = "";

        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml.trim()); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点
            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称

            Element returnCodeElement = rootElt.element("RETURN_CODE");

            String returnCode =  returnCodeElement.getStringValue();

            //交易成功
            if(RETURN_CODE.equals(returnCode))
            {

                Iterator iter = rootElt.elementIterator("QUERYORDER"); // 获取订单支付信息
                while (iter.hasNext()) {
                    Element recordEle = (Element) iter.next();
                    statusCode = recordEle.elementTextTrim("STATUSCODE"); // 支付状态

                }
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return statusCode;
    }


    public static void main(String[] args)
    {
        String xml = "<?xml version = \"1.0\" encoding=\"GB2312\" ?>\n" +
                "<DOCUMENT>\n" +
                "\t<RETURN_CODE>000000</RETURN_CODE>\n" +
                "  <RETURN_MSG></RETURN_MSG>\n" +
                "\t<CURPAGE>1</CURPAGE>\n" +
                "\t<PAGECOUNT>1</PAGECOUNT>\n" +
                "\t<TOTAL>1</TOTAL>\n" +
                "\t<PAYAMOUNT>820.00</PAYAMOUNT>\n" +
                "\t<REFUNDAMOUNT>1.00</REFUNDAMOUNT>\n" +
                "\n" +
                "\t<QUERYORDER>\n" +
                "\t\t<MERCHANTID>105290045112144</MERCHANTID>\n" +
                "\t\t<BRANCHID>310000000</BRANCHID>\n" +
                "\t\t<POSID>100000037</POSID>\n" +
                "\t\t<ORDERID>000319065</ORDERID>\n" +
                "\t\t<ORDERDATE>20081229085159</ORDERDATE>\n" +
                "\t\t<ACCDATE>20100906</ACCDATE>\n" +
                "\t\t<AMOUNT>820.00</AMOUNT>\n" +
                "\t\t<STATUSCODE>1</STATUSCODE>\n" +
                "\t\t<STATUS>3</STATUS>\n" +
                "\t\t<REFUND>1.00</REFUND>\n" +
                "\t\t<SIGN>28f41cd542dc8aa4e00e341de4a3d2afb6121bf28732e5c525ea8e50dcb873c076e601c75124225ce4cba0aacd313ede3b32e378b7bfc486c9ed55b0e0d4137d257258ad517968413f311eb4ee21484af56a01f8a4f45b5341fe011a6348c78d6abf23c8b101e0ce1a5c4daf2314a491af658064524cb9ee38a9610266a5685c</SIGN>\n" +
                "\t</QUERYORDER>\n" +
                "\n" +
                "</DOCUMENT>";
        System.out.println(readStringXml(xml));
    }

    /**
     * 获取支付地址
     * @param driverMer
     * @param payment
     * @return
     */
    public static AjaxResult  getPayQrCode(DriverMerListVo driverMer,String payment,String curCode,String txCode,String bankURL,String RETURNTYPE,String preUrl)
    {

        AjaxResult ajax = AjaxResult.success();
        String MERCHANTID = driverMer.getMerchantid();
        String POSID = driverMer.getPostid();
        String BRANCHID = driverMer.getBranchid();
        String ORDERID = OrderUtil.getBankLsh(MERCHANTID);
        String REMARK1 = "";
        String REMARK2 = "";
        String TIMEOUT = "";
        String PUB32TR2= driverMer.getPub32tr2();

        StringBuffer tmp = new StringBuffer();
        tmp.append("MERCHANTID=");
        tmp.append(MERCHANTID);
        tmp.append("&POSID=");
        tmp.append(POSID);
        tmp.append("&BRANCHID=");
        tmp.append(BRANCHID);
        tmp.append("&ORDERID=");
        tmp.append(ORDERID);
        tmp.append("&PAYMENT=");
        tmp.append(payment);
        tmp.append("&CURCODE=");
        tmp.append(curCode);
        tmp.append("&TXCODE=");
        tmp.append(txCode);
        tmp.append("&REMARK1=");
        tmp.append(REMARK1);
        tmp.append("&REMARK2=");
        tmp.append(REMARK2);
        tmp.append("&RETURNTYPE=");
        tmp.append(RETURNTYPE);
        tmp.append("&TIMEOUT=");
        tmp.append(TIMEOUT);
        tmp.append("&PUB=");
        tmp.append(PUB32TR2);

        Map map = new HashMap();
        map.put("CCB_IBSVersion","V6");
        map.put("MERCHANTID",MERCHANTID);
        map.put("BRANCHID",BRANCHID);
        map.put("POSID",POSID);
        map.put("ORDERID",ORDERID);
        map.put("PAYMENT",payment);
        map.put("CURCODE",curCode);
        map.put("TXCODE",txCode);
        map.put("REMARK1",REMARK1);
        map.put("REMARK2",REMARK2);
        map.put("RETURNTYPE",RETURNTYPE);
        map.put("TIMEOUT",TIMEOUT);
        map.put("MAC", MD5.md5Str(tmp.toString()));
        String ret = HttpClientUtil.httpPost(bankURL, map);
        System.out.println("ret::"+ret);
        String fileType = "html";
        Map paramMap = Maps.newHashMap();
        paramMap.put("content",ret);
        paramMap.put("fileType",fileType);
        String path = HttpClientUtil.httpPost(preUrl + "file/uploadByContent",paramMap);
        path = path.substring(1,path.length());
        ajax.put("qrmsg",preUrl + path);
        return ajax;
    }
}
